package cn.exrick.xboot.common.utils.jiuqi.utils;

import cn.exrick.xboot.common.constant.CommonConstant;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.PushPayload.Builder;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author    : LiYuanzhuo
 * description: 极光推送工具类
 * create time: 2019/8/30 11:14
 */
@Component
@Slf4j
public class JiGuangPushUtil {


    /**
     * 通知推送
     * 备注：推送方式不为空时，推送的值也不能为空；推送方式为空时，推送值不做要求
     * @param type 推送方式：1、“tag”标签推送，2、“alias”别名推送
     * @param value 推送的标签或别名值
     * @param alert 推送的内容
     */
    public static void pushNotice(JPushClient jPushClient ,String type, String value, String alert){
        Builder builder= PushPayload.newBuilder();
        //设置接受的平台，all为所有平台，包括安卓、ios、和微软的
        builder.setPlatform(Platform.all());
        //设置如果用户不在线、离线消息保存的时间
        Options options=Options.sendno();
        //设置为86400为保存一天，如果不设置默认也是保存一天
        options.setTimeToLive(86400l);
        builder.setOptions(options);
        //设置推送方式
        if(type.equals("alias")){
            //根据别名推送
            builder.setAudience(Audience.alias(value));
        }else if(type.equals("tag")){
            //根据标签推送
            builder.setAudience(Audience.tag(value));
        }else{
            //Audience设置为all，说明采用广播方式推送，所有用户都可以接收到
            builder.setAudience(Audience.all());
        }
        //设置为采用通知的方式发送消息
        builder.setNotification(Notification.alert(alert));
        PushPayload pushPayload=builder.build();
        try{
            //进行推送，实际推送就在这一步
            PushResult pushResult=jPushClient.sendPush(pushPayload);
        }catch(Exception e){
            //e.printStackTrace();
        }
    }
    /**
     * 自定义消息推送(注：Notification)
     * 备注：推送方式不为空时，推送的值也不能为空；推送方式为空时，推送值不做要求
     * @param type 推送方式：1、“tag”标签推送，2、“alias”别名推送
     * @param value 推送的标签或别名值
     * @param alert 推送的内容
     */
    public static PushResult pushMsg(JPushClient jPushClient, String type, String value, String alert){
        Builder builder= PushPayload.newBuilder();
        //设置接受的平台
        builder.setPlatform(Platform.all());
        if(type.equals("alias")){
            //别名推送
            builder.setAudience(Audience.alias(value));
        }else if(type.equals("tag")){
            //标签推送
            builder.setAudience(Audience.tag(value));
        }else{
            //Audience设置为all，说明采用广播方式推送，所有用户都可以接收到
            builder.setAudience(Audience.all());
        }
        Message.Builder newBuilder=Message.newBuilder();

        Notification.Builder nmessage=  Notification.newBuilder();
        //消息内容
        //newBuilder.setMsgContent(alert);
        //--------------------
        Map<String, String> extras = new HashMap<String, String>();
        extras.put(CommonConstant.APPROVAL_UPDATE,"true");
        extras.put("body",alert);
        newBuilder.setMsgContent("审批MsgContent").setTitle("审批").addExtras(extras);
        //--------------------
        nmessage.setAlert("审批Alert");

        //Message message=newBuilder.build();
        Notification notification = nmessage.build();

        //builder.setMessage(message);
        builder.setNotification(notification);
        //log.info("推送出去的验证码：" + notification);
        PushPayload pushPayload=builder.build();
        PushResult pushResult = new PushResult();

        try{
             pushResult=jPushClient.sendPush(pushPayload);
        }catch(Exception e){
            //e.printStackTrace();
        }
        return pushResult;
    }

    /**
     * 安卓与ios平台，通过别名推送
     * @param alias     别名
     * @param content   推送内容
     * @param key       拓展字段key值
     * @param value     拓展字段value
     * @return
     */
   /* public static PushPayload buildPushObject_all_alias_alert(String alias, String content,String key,String value) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.newBuilder()
                        .setAlert(content)
                        .addPlatformNotification(AndroidNotification.newBuilder().addExtra(key,value).setTitle("审批登录")
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setBadge(5)
                                .setSound("default").addExtra(key,value)
                                .build())
                        .build())
                .build();
    }*/

    /**
     *
     * @param jPushClient
     * @param type 推送方式：1、“tag”标签推送，2、“alias”别名推送
     * @param value 推送的标签或别名值
     * @param map 别名集合
     * @param alert  标题？
     * @param content 推送内容
     */
    public static PushResult pushAPP(JPushClient jPushClient, String type, String value,Map<String ,String> map,String alert,String content){
        Builder builder= PushPayload.newBuilder();

        //设置接受的平台，all为所有平台，包括安卓、ios、和微软的
        builder.setPlatform(Platform.all());
        //设置如果用户不在线、离线消息保存的时间
        Options options=Options.sendno();
        //设置为86400为保存一天，如果不设置默认也是保存一天
        options.setTimeToLive(86400l);
        options.setApnsProduction(true);
        builder.setOptions(options);
        //设置推送方式
        if(type.equals("alias")){
            //根据别名推送
            builder.setAudience(Audience.alias(value));
        }else if(type.equals("tag")){
            //根据标签推送
            builder.setAudience(Audience.tag(value));
        }else{
            //Audience设置为all，说明采用广播方式推送，所有用户都可以接收到
            builder.setAudience(Audience.all());
        }

        //设置为采用通知的方式发送消息
        builder.setNotification(Notification.newBuilder()
                .addPlatformNotification(IosNotification.newBuilder()
                        .setAlert(alert)//APP开发说这是标题?
                        .setBadge(5)
                        .addExtras(map)
                        .build()

                )
                .addPlatformNotification(AndroidNotification.newBuilder()
                        .setAlert(alert)//APP开发说这是标题?

                        .addExtras(map)
                        .build())
                        .build()
        ).setMessage(Message.content(content));

        PushPayload pushPayload=builder.build();

        PushResult pushResult = new PushResult();
        try{
            //进行推送，实际推送就在这一步
            pushResult= jPushClient.sendPush(pushPayload);

        }catch(Exception e){
            /**
             * njp 20200302
             * 优化极光平台的调用在调用失败时将链接关闭 begin
             */
            log.error("调用极光平台推送SDK失败 "+new Date());
            jPushClient.close();
            /**
             * njp 20200302
             * 优化极光平台的调用在调用失败时将链接关闭 end
             */

            //e.printStackTrace();
        }
        return pushResult;
    }






    /**
     *njp 20200424推送角标 ios
     * @param jPushClient
     * @param type 推送方式：1、“tag”标签推送，2、“alias”别名推送
     * @param value 推送的标签或别名值(username)
     * @param alert  标题？
     * @param content 推送内容
     */
    public static PushResult pushAngleIos(JPushClient jPushClient, String type, String value,String alert,String content,int backlogNum){
        Builder builder= PushPayload.newBuilder();

        //设置接受的平台，all为所有平台，包括安卓、ios、和微软的
        builder.setPlatform(Platform.all());
        //设置如果用户不在线、离线消息保存的时间
        Options options=Options.sendno();
        //设置为86400为保存一天，如果不设置默认也是保存一天
        options.setTimeToLive(86400l);
        options.setApnsProduction(true);
        builder.setOptions(options);
        //设置推送方式
        if(type.equals("alias")){
            //根据别名推送
            builder.setAudience(Audience.alias(value));
        }else if(type.equals("tag")){
            //根据标签推送
            builder.setAudience(Audience.tag(value));
        }else{
            //Audience设置为all，说明采用广播方式推送，所有用户都可以接收到
            builder.setAudience(Audience.all());
        }
        if(CommonConstant.ALERT_OFF.equals(alert)) {
            //去掉标题（在app中就不会有通知弹出）
            builder.setNotification(Notification.newBuilder()
                    .addPlatformNotification(IosNotification.newBuilder()
                            .setAlert("")
                            .setBadge(backlogNum)
                            .build()
                    )
                    .build()
            ).setMessage(Message.content(content));
        }else{
            builder.setNotification(Notification.newBuilder()
                    .addPlatformNotification(IosNotification.newBuilder()
                            .setAlert(alert)//APP开发说这是标题?
                            .setBadge(backlogNum)
                            .build()
                    )
                    .build()
            ).setMessage(Message.content(content));
        }

                PushPayload pushPayload=builder.build();
                PushResult pushResult = new PushResult();

        try{
            //进行推送，实际推送就在这一步
            pushResult= jPushClient.sendPush(pushPayload);

        }catch(Exception e){
            /**
             * njp 20200302
             * 优化极光平台的调用在调用失败时将链接关闭 begin
             */
            log.error("调用极光平台推送SDK失败 "+new Date());
            jPushClient.close();
            /**
             * njp 20200302
             * 优化极光平台的调用在调用失败时将链接关闭 end
             */

           // e.printStackTrace();
        }
        return pushResult;
    }

    /**
     *njp 20200424推送安卓角标，由于安卓角标推送特殊所以与ios的角标推送分开方便后续优化
     * @param jPushClient
     * @param type 推送方式：1、“tag”标签推送，2、“alias”别名推送
     * @param value 推送的标签或别名值(username)
     * @param alert  标题？
     * @param backlogNum 角标数量
     *
     */
    public static PushResult pushAngleAndroid(JPushClient jPushClient, String type, String value,String alert,int backlogNum) {
            //目前是每有一条待办就推送一条增量backlogNum的值应该是1
        PushResult pushResult = new PushResult();
        try{
        PushPayload pushPayload = PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(value))
                .setNotification(Notification
                        .newBuilder().setAlert("Hi,JPush")
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(alert)
                                .addCustom("badge_add_num", backlogNum)
                                .addCustom("badge_class","com.jiuqi.gmt.tj.WelcomeActivity")
                                .build()).build())
                .setOptions(Options.newBuilder().setApnsProduction(false).build())
                .build();



            //进行推送，实际推送就在这一步
            pushResult= jPushClient.sendPush(pushPayload);

            /**
             * test
             */
            //jPushClient.sendPush(buildPushObject_ios_audienceMore_messageWithExtras());
            /**
             * test
             */

        }catch(Exception e){
            log.error("调用极光平台推送SDK失败 "+new Date());
            jPushClient.close();
            //e.printStackTrace();
        }
        return pushResult;
    }



    /**
     *njp  向安卓APP推送待办角标的总数
     * @param jPushClient
     * @param value 推送的标签或别名值
     * @param map 别名集合
     */
    public static PushResult pushAngleAndroid(JPushClient jPushClient, String value,Map<String ,String> map){
        //目前是每有一条待办就推送一条增量backlogNum的值应该是1
        PushResult pushResult = new PushResult();
        try{
            //进行推送，实际推送就在这一步
            /**
             * test
             */
            jPushClient.sendPush(buildPushObject_ios_audienceMore_messageWithExtras(value,map));
            /**
             * test
             */

        }catch(Exception e){
            log.error("调用极光平台推送SDK失败 "+new Date());
            jPushClient.close();
            //e.printStackTrace();
        }
        return pushResult;
    }



    public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras(String value,Map<String ,String> map) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.newBuilder()
                        //根据别名推送
                        .addAudienceTarget(AudienceTarget.alias(value))
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent("AngleMinus")
                        .addExtras(map)
                        .build())
                .build();
    }

                /*public static void main(String[] args) {
                //JPushClient jPushClient = new JPushClient("1a7382474bbda36da40cc4b1","076313340ce35cdc05d7265f");
                JPushClient jPushClient = new JPushClient("7d7f6ec6167ab9bb66dfb459","80d5d89113aa897e2804474b");
            //给标签为kefu的用户进行消息推送
            JiGuangPushUtil.pushAngleIos( jPushClient, "alias", "njp",CommonConstant.ALERT_OFF,"BacklogAngle",15);

    }*/
    }





  /*  public static void main(String[] args) {
        //JPushClient jPushClient = new JPushClient("1a7382474bbda36da40cc4b1","076313340ce35cdc05d7265f");
        JPushClient jPushClient = new JPushClient("b52149da16c51e45c69d755c","70fcf39f0a41f10abfde196a");
//给标签为kefu的用户进行消息推送
        //JiGuangPushUtil.pushAPP(jPushClient,"alias","test","你有新的任务，请及时处理dgfhdsfg");
    }*/

